package com.base.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.base.entity.User;
import com.base.entity.dto.PassDto;
import com.base.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-11
 */
@RestController
@RequestMapping("/user")
@Api(tags = "身份验证")
@CrossOrigin
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    @ApiOperation("登录")
    public SaResult login(@RequestBody User user) {
        try {
            User foundUser = userService.getOne(new QueryWrapper<User>()
                    .eq("username", user.getUsername()));
            if (foundUser == null) {
                return SaResult.error("账号不存在！");
            }
            if (foundUser.getPassword().equals(user.getPassword())) {
                StpUtil.login(foundUser.getId());
                StpUtil.getSession().set("role", foundUser.getRole());
//            数据
                HashMap<String, Object> map = new HashMap<>();
                map.put("token", StpUtil.getTokenInfo());
                foundUser.setPassword("");
                map.put("user", foundUser);
                return SaResult.data(map);
            } else {
                return SaResult.error("密码错误！");
            }
        }catch (Exception e){
            return SaResult.error("登录失败！");
        }
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public SaResult register(@RequestBody User user) {
        if (userService.getOne(new QueryWrapper<User>()
                .eq("username", user.getUsername())) != null) {
            return SaResult.error("注册失败，用户名已存在！");
        }
        userService.save(user);
        return SaResult.ok();
    }

    @PostMapping("/updatePass")
    @ApiOperation("修改密码")
    public SaResult register(@RequestBody PassDto passDto) {
//        原密码
        User user = userService.getById(passDto.getUserId());
        if (user.getPassword().equals(passDto.getOldPass())) {
            user.setPassword(passDto.getNewPass());
            userService.updateById(user);
        } else {
            return SaResult.code(201).setMsg("原密码输入错误！");
        }
        return SaResult.ok();
    }


}
